package com.ld.shieldsb.common.web.tag;

import java.io.IOException;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.web.tag.model.TokenModel;
import com.ld.shieldsb.common.web.util.Web;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

/**
 * 搜索标签转义，使用只读的加密key(会保存的不要使用)
 * 
 * @ClassName QueryParamTag
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年3月28日 下午3:54:16
 *
 */
@EqualsAndHashCode(callSuper = false)
@Data
@Slf4j
public class CsrfTokenTag extends TagSupportBasicTag {
    private static final String TOKEN_KEY = Web.Attr.SESSION_TOKEN_KEY;

    /**
     * @Fields serialVersionUID
     */
    private static final long serialVersionUID = 2841796557773598128L;

    @Override
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();// 指定输入流，用于页面输出分页信息、
        HttpSession session = pageContext.getSession();
//        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        Object parameterName = "csftToke";
        Object token = "csftToke";
        if (session != null) {
            TokenModel csftToken = (TokenModel) session.getAttribute(TOKEN_KEY); //
            if (csftToken == null) {
                csftToken = new TokenModel(StringUtils.getRandomStr(18));
                session.setAttribute(TOKEN_KEY, csftToken);
            }
            parameterName = csftToken.getParameterName();
            token = csftToken.getToken();
        }
        StringBuffer sb = new StringBuffer();
        sb.append("<input id=\"csrfTokenInput\" type=\"hidden\" name=\"");// 构建StringBuffer对象，用户拼接分页标签
        sb.append(parameterName);// 构建StringBuffer对象，用户拼接分页标签
        sb.append("\" value=\"");// 构建StringBuffer对象，用户拼接分页标签
        sb.append(token);// 构建StringBuffer对象，用户拼接分页标签
        sb.append("\" />");// 构建StringBuffer对象，用户拼接分页标签
        try {
            out.print(sb);
        } catch (IOException e) {
            log.error("", e);
        }
        return SKIP_BODY;
    }

    @Override
    public int doStartTag() throws JspException {
        return EVAL_PAGE;
    }

}
